//
//  AssetGridViewController.swift
//  PhotoKitDemo
//
//  Created by 舒磊明 on 2019/2/21.
//  Copyright © 2019 舒磊明. All rights reserved.
//

import UIKit
import Photos

private let reuseIdentifier = "Cell"

class AssetGridViewController: UICollectionViewController {

    var allPhotos: PHFetchResult<PHAsset>!
    var imageManager = PHCachingImageManager()
    var itemSize: CGSize?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 设置背景颜色
        collectionView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        
        // 一直可以垂直滑动
        collectionView.alwaysBounceVertical = true
        
        // 注册GridCell
        self.collectionView!.register(GridCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // 获取所有图片
        let allPhotosOption = PHFetchOptions()
        allPhotosOption.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        allPhotos = PHAsset.fetchAssets(with: allPhotosOption)
    }
    
    //MARK: - CollectionView Delegate
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return allPhotos.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! GridCell
        cell.backgroundColor = UIColor.red
        let asset = allPhotos.object(at: indexPath.item)
        cell.representedAssetIdentifier = asset.localIdentifier
        imageManager.requestImage(for: asset, targetSize: itemSize ?? CGSize.zero, contentMode: .aspectFill, options: nil) { (image, _) in
            if cell.representedAssetIdentifier == asset.localIdentifier {
                cell.imageV.image = image
            }
        }
        
        return cell
    }
}

class GridCell: UICollectionViewCell {
    
    var representedAssetIdentifier: String!
    lazy var imageV = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageV)
        imageV.frame = contentView.bounds
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
